import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/user/infomation.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';

import '../../widget/icon_text.dart';
import 'moment.dart';

//粉丝详情
class UserProfileUi extends StatelessWidget {
  final String memberId;

  const UserProfileUi({Key? key, required this.memberId}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _UserProfileWidget(
      memberId: memberId,
    );
  }
}

class _UserProfileWidget extends StatefulWidget {
  final String memberId;

  const _UserProfileWidget({Key? key, required this.memberId})
      : super(key: key);

  @override
  State<_UserProfileWidget> createState() => _UserProfileWidgetState();
}

class _UserProfileWidgetState extends State<_UserProfileWidget>
    with TickerProviderStateMixin {
  late double _screenWidth;
  final _titles = [
    "基本资料",
    "动态",
  ];
  late TabController _tabController;
  late PageController _pageController;

  // Map<String, dynamic>? _userInfo;
  Map _userInfo = {};

  void _onTabChanged(int index) {
    _pageController.animateToPage(index,
        duration: const Duration(milliseconds: 300), curve: Curves.ease);
  }

  void _onPageChanged(int index) {
    _tabController.animateTo(index,
        duration: const Duration(milliseconds: 300));
  }

  @override
  void dispose() {
    _tabController.dispose();
    _pageController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _titles.length, vsync: this);
    _pageController = PageController();
    _getUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    _screenWidth = screenSize.width;

    return AppWidget.navTitleBar(
      bgColor: Colors.white,
      title: '',
      childWidget: Stack(
        children: [_buildContent()],
      ),
    );
  }

  Widget _buildContent() {
    return NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [
          _buildBanner(),
          _buildUserInfo(),
        ];
      },
      body: Column(
        children: [_buildTabBar(), Expanded(child: _buildPageView())],
      ),
    );
  }

  /// 轮播图
  Widget _buildBanner() {
    List<String> imgList = _userInfo?["memberAvatarList"] ?? [];
    print('=========');
    print(imgList);
    final avatar = _userInfo?["profilePhoto"];
    if (imgList.isEmpty && avatar != null && avatar.toString().isNotEmpty) {
      for (var item in _userInfo?["photos"]) {
        imgList.add(item['profilePhoto']);
      }
    }
    double indicatorWidth =
        (_screenWidth - 24 - (imgList.length - 1) * 2.5) / imgList.length;
    return SliverToBoxAdapter(
      child: AspectRatio(
        //设置图片的展示比例之后，可以不设置外层的宽度，或者设置成infinity
        aspectRatio: 1 / 1,
        child: Swiper(
          itemCount: imgList.length,
          itemBuilder: (BuildContext context, int index) {
            // return Image.network(Provider.fixAvatar(imgList[index]),
            //   fit: BoxFit.fill,
            // );
            return Stack(
              children: [
                Center(
                  child: Container(
                      // width: 350,
                      height: 450,
                      padding: const EdgeInsets.fromLTRB(0, 15, 0, 15),
                      color: Colors.white,
                      // padding: const EdgeInsets.symmetric(vertical: 5, ),
                      child: ClipRRect(
                        // borderRadius: BorderRadius.circular(5),
                        child: Image.network(
                          imgList[index],
                          fit: BoxFit.fill,
                        ),
                      )),
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Container(
                      margin: const EdgeInsets.only(top: 250, right: 30),
                      // width: 170,
                      // height: 151,

                      // color: Colors.white,
                      child: _userInfo['singleState'] == 1
                          ? Image.asset(
                              // "images/ic_lunboSingle.png",
                              "images/ic_fdsbzh.png",
                              width: 126,
                              height: 96,
                              fit: BoxFit.cover,
                            )
                          : Container(),
                    ),
                  ],
                )
              ],
            );
            // return Container(
            //     margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 14),
            //     child: ClipRRect(
            //       borderRadius: BorderRadius.circular(5),
            //       child: Image.network(
            //         Provider.fixAvatar(Provider.fixAvatar(imgList[index])),
            //         fit: BoxFit.contain,
            //       ),
            //     )
            //
            // );
          },
          //分页指示器
          pagination: SwiperPagination(
              alignment: Alignment.topCenter,
              builder: RectSwiperPaginationBuilder(
                  color: const Color(0x76FFFFFF),
                  activeColor: Colors.white,
                  size: Size(indicatorWidth, 4),
                  activeSize: Size(indicatorWidth, 4),
                  space: 2.5)),
          //页面上的左右箭头
          control: null,
          //自动轮播
          autoplay: false,
          loop: false,
        ),
      ),
    );
  }

  /// 用户简介
  Widget _buildUserInfo() {
    return SliverToBoxAdapter(
        child: Column(
      children: [
        Container(
          padding:
              const EdgeInsets.only(top: 12, left: 12, right: 12, bottom: 10),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
            width: 1,
            color: ThemeColor.dividerColor,
          ))),

          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text(
                        _userInfo?["nickName"] ?? "",
                        style: TextStyle(
                            fontSize: 16,
                            color: ThemeColor.textColor,
                            overflow: TextOverflow.ellipsis),
                      ),
                      const SizedBox(
                        width: 5,
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Container(
                        width: 60,
                        height: 20,
                        alignment: Alignment.center,
                        decoration: ShapeDecoration(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(5),
                          ),
                          color: _userInfo['isRealAuth'] == 1
                              ? const Color.fromRGBO(127, 105, 217, 0.14)
                              : const Color.fromRGBO(170, 170, 170, 0.14),
                        ),
                        child: Text.rich(
                          TextSpan(
                            style: TextStyle(
                                fontSize: 10,
                                color: _userInfo['isRealAuth'] == 1
                                    ? const Color(0xFF7F69D9)
                                    : const Color.fromRGBO(170, 170, 170, 1)),
                            children: [
                              WidgetSpan(
                                child: Image.asset(
                                    _userInfo['isRealAuth'] == 1
                                        ? 'images/ic_myStatusSec.png'
                                        : 'images/ic_myNoStatusSec.png',
                                    width: 10,
                                    height: 10),
                              ),
                              TextSpan(
                                text: _userInfo['isRealAuth'] == 1
                                    ? ' 已实名'
                                    : ' 未实名',
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              const SizedBox(
                height: 5,
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Container(
                        alignment: Alignment.center,
                        decoration: ShapeDecoration(
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                            color: _userInfo['realSex'] == 2
                                ? ThemeColor.mainColor
                                : Colors.blue),
                        width: 40,
                        height: 16,
                        child: IconText(
                          _userInfo['age'].toString() ?? '',
                          icon: Icon(
                              _userInfo['realSex'] == 2
                                  ? Icons.female
                                  : Icons.male,
                              color: Colors.white),
                          iconSize: 12,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 5,
                      ),
                      Image.asset(
                        "images/ic_path.png",
                        width: 11,
                        height: 13,
                      ),
                      const SizedBox(
                        width: 3,
                      ),
                      Text(
                        '${_userInfo['homeAddr'] ?? ''}',
                        style:
                            const TextStyle(fontSize: 12, color: Colors.grey),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Image.asset(
                        'images/ic_houseimg.png',
                        width: 16,
                        height: 16,
                      ),
                      const SizedBox(
                        width: 5,
                      ),
                      Image.asset(
                        'images/ic_carimg.png',
                        width: 16,
                        height: 16,
                      ),
                    ],
                  ),
                ],
              ),
              // const SizedBox(height: 5,),
            ],
          ),
        ),
      ],
    ));
  }

  /// 标签选项
  Widget _buildTabBar() {
    return TabBar(
      // padding: EdgeInsets.only(top: 10, left: 0, right: 60, bottom: 0),
      // padding: EdgeInsets.only(left: 0),
      // padding: EdgeInsets.symmetric(horizontal: 100),
      padding: EdgeInsets.symmetric(horizontal: (_screenWidth - 230) / 2),
      // labelPadding: const EdgeInsets.symmetric(horizontal: 10),
      controller: _tabController,
      tabs: _titles.map((e) => Tab(text: e)).toList(),
      labelColor: ThemeColor.appColor,
      labelStyle: TextStyle(
          color: ThemeColor.textColor,
          fontWeight: FontWeight.bold,
          fontSize: 16),
      unselectedLabelColor: ThemeColor.textColorSecond,
      unselectedLabelStyle: TextStyle(color: ThemeColor.appColor, fontSize: 14),
      isScrollable: false,
      indicatorColor: ThemeColor.appColor,
      indicatorSize: TabBarIndicatorSize.label,
      indicatorPadding: const EdgeInsets.symmetric(horizontal: 2),
      indicatorWeight: 6,
      onTap: _onTabChanged,
    );
  }

  /// view page
  Widget _buildPageView() {
    return PageView.builder(
      controller: _pageController,
      physics: const BouncingScrollPhysics(),
      itemCount: _titles.length,
      onPageChanged: _onPageChanged,
      itemBuilder: (context, index) {
        return index == 0
            ? ProfileInfo(
                userInfo: _userInfo,
              )
            : ProfileMoment(
                memberId: _userInfo?['id'] ?? "",
              );
      },
    );
  }

  _getUserInfo() {
    print('bbbb ${widget.memberId}');
    loading(() async {
      final res = await Api.getInstance().getFriendInfo(widget.memberId);
      print('vvvv  ${res['data']['easeuserId']}');
      if (res['code'] == 0) {
        final data = res['data'];
        final mcs = data['mcs'];
        setState(() {
          _userInfo = data;

          print('============');
          print(data['maritalStatus']);
          String maritalStatus = '';

          if (data['maritalStatus'] == 0) {
            maritalStatus = '未婚';
          }

          if (data['maritalStatus'] == 1) {
            maritalStatus = '已婚';
          }

          if (data['maritalStatus'] == 2) {
            maritalStatus = '再婚';
          }

          if (data['maritalStatus'] == 3) {
            maritalStatus = '离异';
          }

          if (data['maritalStatus'] == 4) {
            maritalStatus = '丧偶';
          }

          _userInfo['maritalStatusNew'] = maritalStatus;

          String childNum = '';
          // if(data['childNum'] == 0) {
          //   childNum = '不抚养';
          // } else {
          //
          //   childNum = '抚养';
          // }

          _userInfo['childNumNew'] = childNum;

          String realSex = '';

          if (data['realSex'] == 2) {
            realSex = '女';
          } else {
            realSex = '男';
          }

          _userInfo['realSexNew'] = realSex.toString();

          String edu = '';
          if (data['edu'] == 0) {
            edu = '小学';
          } else if (data['edu'] == 1) {
            edu = '初中';
          } else if (data['edu'] == 2) {
            edu = '高中';
          } else if (data['edu'] == 3) {
            edu = '大专';
          } else if (data['edu'] == 4) {
            edu = '本科';
          } else if (data['edu'] == 5) {
            edu = '硕士';
          } else if (data['edu'] == 6) {
            edu = '博士';
          } else if (data['edu'] == 7) {
            edu = '教授';
          }

          String eduNew = '';
          if (mcs['edu'] == 0) {
            eduNew = '小学';
          } else if (mcs['edu'] == 1) {
            eduNew = '初中';
          } else if (mcs['edu'] == 2) {
            eduNew = '高中';
          } else if (mcs['edu'] == 3) {
            eduNew = '大专';
          } else if (mcs['edu'] == 4) {
            eduNew = '本科';
          } else if (mcs['edu'] == 5) {
            eduNew = '硕士';
          } else if (mcs['edu'] == 6) {
            eduNew = '博士';
          } else if (mcs['edu'] == 7) {
            eduNew = '教授';
          }

          _userInfo['eduNew'] = edu;
          _userInfo['cmseduNew'] = eduNew;

          String incomeVal = '';
          if (data['incomeVal'] == 0) {
            incomeVal = '5万~10万';
          } else if (data['incomeVal'] == 1) {
            incomeVal = '10万~20万';
          } else if (data['incomeVal'] == 2) {
            incomeVal = '20万~50万';
          } else if (data['incomeVal'] == 3) {
            incomeVal = '50万~100万';
          } else if (data['incomeVal'] == 4) {
            incomeVal = '100万~300万';
          } else if (data['incomeVal'] == 5) {
            incomeVal = '300万以上';
          } else if (data['incomeVal'] == 6) {
            incomeVal = '';
          }
          String incomeValnew = '';

          if (mcs['incomeVal'] == 0) {
            incomeValnew = '5万~10万';
          } else if (mcs['incomeVal'] == 1) {
            incomeValnew = '10万~20万';
          } else if (mcs['incomeVal'] == 2) {
            incomeValnew = '20万~50万';
          } else if (mcs['incomeVal'] == 3) {
            incomeValnew = '50万~100万';
          } else if (mcs['incomeVal'] == 4) {
            incomeValnew = '100万~300万';
          } else if (mcs['incomeVal'] == 5) {
            incomeValnew = '300万以上';
          } else if (mcs['incomeVal'] == 6) {
            incomeValnew = '';
          }

          _userInfo['incomeValNew'] = incomeVal;
          _userInfo['mcsincomeValNew'] = incomeValnew;

          String buyCar = '';
          String buyCarNew = '';
          if (data['buyCar'] == 1) {
            buyCar = '有车';
          } else {
            buyCar = '无车';
          }

          if (mcs['buyCar'] == 1) {
            buyCarNew = '有车';
          } else {
            buyCarNew = '无车';
          }

          _userInfo['buyCarNew'] = buyCar;
          _userInfo['mcsbuyCarNew'] = buyCarNew;

          String buyChase = '';
          String buyChaseNew = '';
          if (data['buychase'] == 1) {
            buyChase = '有房';
          } else {
            buyChase = '无房';
          }

          if (mcs['purchase'] == 1) {
            buyChaseNew = '有房';
          } else {
            buyChaseNew = '无房';
          }

          _userInfo['buychaseNew'] = buyChase;
          _userInfo['mcsbuychaseNew'] = buyChaseNew;

          String aat = '';
          if (data['aat'] == 1) {
            aat = '吸烟喝酒';
          } else {
            aat = '不吸烟喝酒';
          }

          _userInfo['aatNew'] = aat;

          _userInfo['mcsageStartNew'] = mcs['ageStart'];
          _userInfo['mcsageEndNew'] = mcs['ageEnd'];
          _userInfo['mcsweightStartNew'] = mcs['weightStart'];
          _userInfo['mcsweightEndNew'] = mcs['weightEnd'];
          _userInfo['mcsheightStartNew'] = mcs['heightStart'];
          _userInfo['mcsheightEndNew'] = mcs['heightEnd'];
        });
      } else {
        ThemeSnackBar.show(context, res['msg']);
      }
    });
  }
}
